import React, { useState, useEffect } from 'react';
import { message } from 'antd';
import { ApiService } from '../services/api';
import MapComponent from '../components/MapComponent';
import './ContactPage.css';

const ContactPage = () => {
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    email: '',
    verificationCode: ''
  });

  const [verificationData, setVerificationData] = useState({
    code: '',
    eventId: ''
  });

  const [companyData, setCompanyData] = useState({
    companyName: '',
    address: '',
    mobile: '',
    email: '',
    longitude: '',
    latitude: ''
  });

  const [loading, setLoading] = useState(false);
  const [verificationLoading, setVerificationLoading] = useState(false);

  // 页面加载时获取验证码和公司详情
  useEffect(() => {
    fetchVerificationCode();
    fetchCompanyDetail();
  }, []);

  // 获取验证码
  const fetchVerificationCode = async () => {
    try {
      setVerificationLoading(true);
      const response = await ApiService.getVerificationCode();
      
      if (response.code === '0000' && response.data) {
        setVerificationData({
          code: response.data.verificationCode,
          eventId: response.data.eventId
        });
      } else {
        message.error('获取验证码失败');
      }
    } catch (error) {
      console.error('获取验证码失败:', error);
      message.error('获取验证码失败，请重试');
    } finally {
      setVerificationLoading(false);
    }
  };

  // 获取公司详情
  const fetchCompanyDetail = async () => {
    try {
      const response = await ApiService.getCompanyDetail();
      if (response.code === '0000' && response.data) {
        setCompanyData({
          companyName: response.data[0].companyName || '',
          address: response.data[0].address || '',
          mobile: response.data[0].mobile || '',
          email: response.data[0].email || '',
          longitude: response.data[0].longitude || '',
          latitude: response.data[0].latitude || ''
        });
      } else {
        console.warn('获取公司详情失败，使用默认数据');
      }
    } catch (error) {
      console.error('获取公司详情失败:', error);
      console.warn('使用默认公司信息');
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 表单验证
    if (!formData.title || !formData.content || !formData.email || !formData.verificationCode) {
      message.error('请填写所有必填字段');
      return;
    }

    if (!verificationData.eventId) {
      message.error('验证码已过期，请刷新验证码');
      return;
    }

    try {
      setLoading(true);
      
      const response = await ApiService.submitCommentMessage(
        formData.title,
        formData.content,
        formData.email,
        formData.verificationCode,
        verificationData.eventId
      );

      if (response.code === '0000') {
        message.success('留言提交成功！我们会尽快与您联系。');
        // 重置表单
        setFormData({
          title: '',
          content: '',
          email: '',
          verificationCode: ''
        });
        // 重新获取验证码
        fetchVerificationCode();
      } else {
        message.error(response.message || '提交失败，请重试');
      }
    } catch (error) {
      console.error('提交留言失败:', error);
      message.error('提交失败，请检查网络连接后重试');
    } finally {
      setLoading(false);
    }
  };

  // 根据公司数据动态生成联系信息
  const contactInfo = [
    {
      icon: "🏢",
      title: "公司名称",
      content: companyData.companyName || "北京灵动无界科技有限公司"
    },
    {
      icon: "📍",
      title: "公司地址",
      content: companyData.address || "北京通州区金融街武夷融御4号楼901"
    },
    {
      icon: "📞",
      title: "联系电话",
      content: companyData.mobile || "13693241607"
    },
    {
      icon: "📧",
      title: "邮箱地址",
      content: companyData.email || "infinite_agility@163.com"
    },
  ];

  return (
    <div className="contact-page">
      <div className="container">
        <div className="page-header">
          <h1>联系我们</h1>
          <p>我们期待与您合作，为您提供专业的科技产品解决方案</p>
        </div>

        <div className="contact-content">
          <div className="contact-info-section">
            <h2>联系信息</h2>
            <div className="contact-info-grid">
              {contactInfo.map((info, index) => (
                <div key={index} className="contact-info-card">
                  <div className="contact-icon">{info.icon}</div>
                  <div className="contact-details">
                    <h3>{info.title}</h3>
                    <p>{info.content}</p>
                  </div>
                </div>
              ))}
            </div>

            <div className="qr-code-section">
              <h3>扫一扫关注我们</h3>
              <div className="qr-code-container">
                <div className="qr-code-placeholder">
                  <div className="qr-code-image">
                    {/* <img 
                      src="https://via.placeholder.com/150x150/4A90E2/FFFFFF?text=QR+Code" 
                      alt="微信二维码" 
                      className="qr-code-img"
                    /> */}
                    <div className="qr-placeholder">📱</div>
                  </div>
                  <p className="qr-code-text">微信扫码关注</p>
                </div>
              </div>
            </div>
          </div>

          <div className="contact-form-section">
            <h2>在线留言</h2>
            <form className="contact-form" onSubmit={handleSubmit}>
              <div className="form-group">
                <label htmlFor="title">留言标题 *</label>
                <input
                  type="text"
                  id="title"
                  name="title"
                  value={formData.title}
                  onChange={handleInputChange}
                  placeholder="请输入留言标题"
                  required
                />
              </div>

              <div className="form-group">
                <label htmlFor="email">电子邮箱 *</label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  placeholder="请输入您的邮箱地址"
                  required
                />
              </div>

              <div className="form-group">
                <label htmlFor="content">留言内容 *</label>
                <textarea
                  id="content"
                  name="content"
                  rows="5"
                  value={formData.content}
                  onChange={handleInputChange}
                  placeholder="请详细描述您的需求或问题..."
                  required
                ></textarea>
              </div>

              <div className="form-group verification-group">
                <label htmlFor="verificationCode">验证码 *</label>
                <div className="verification-input-group">
                  <input
                    type="text"
                    id="verificationCode"
                    name="verificationCode"
                    value={formData.verificationCode}
                    onChange={handleInputChange}
                    placeholder="请输入验证码"
                    required
                    className="verification-input"
                  />
                  <div className="verification-code-display">
                    {verificationLoading ? (
                      <div className="verification-loading">加载中...</div>
                    ) : verificationData.code ? (
                      <div className="verification-code">
                        {verificationData.code}
                      </div>
                    ) : (
                      <div className="verification-error">验证码获取失败</div>
                    )}
                    <button 
                      type="button" 
                      className="refresh-btn"
                      onClick={fetchVerificationCode}
                      disabled={verificationLoading}
                    >
                      刷新
                    </button>
                  </div>
                </div>
              </div>

              <button 
                type="submit" 
                className="submit-btn"
                disabled={loading}
              >
                {loading ? '提交中...' : '发送消息'}
              </button>
            </form>
          </div>
        </div>

        <div className="map-section-full">
          <h2>地图位置</h2>
          <MapComponent 
            longitude={companyData.longitude}
            latitude={companyData.latitude}
            address={companyData.address}
            companyName={companyData.companyName}
          />
        </div>
      </div>
    </div>
  );
};

export default ContactPage;
